<template>
  <van-uploader v-if="!capture"
      :max-count="maxFileCount || 1"
      :before-delete="beforeDelete"
      v-model="fileList"
      :after-read="afterRead"
      :disabled="!!disabled"
      :deletable="deletable"
      >
      <template #preview-cover="file">
        <div v-if="file.shortTime" class="preview-cover van-ellipsis">{{ file.shortTime }}</div>
      </template>
    </van-uploader>
  <van-uploader v-else
      :capture="capture" accept="image/*" 
      :max-count="maxFileCount || 1"
      :before-delete="beforeDelete"
      v-model="fileList"
      :after-read="afterRead"
      :disabled="!!disabled"
      :deletable="deletable"
      >
      <template #preview-cover="file">
        <div v-if="file.shortTime" class="preview-cover van-ellipsis">{{ file.shortTime }}</div>
      </template>
  </van-uploader>    
</template>
<script>
import { defineComponent, reactive } from "vue"
import CORSSDK from 'cos-js-sdk-v5'
import http from '../../http/index.js'
import { showConfirmDialog } from 'vant'
import moment from 'moment'

export default defineComponent({
props: ['files', 'type', 'maxFileCount', 'capture', 'disabled', 'deletable'],
name: "upload",
setup(props, { emit }) {
  return reactive({
    cors: {},
    corsConfig: {
      bucket: 'projectimg-1256680128', /* 填入您自己的存储桶，必须字段 */
      region: 'ap-beijing',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
      key: 'lpm/', /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
    },
    fileList: []
  })
},
watch: {
  'files': {
    deep: true, //深度监听设置为 true
    handler: function(newV,oldV){
      if(!newV) {
        this.fileList = []
      }
      if (newV && this.fileList.length === 0) {
        newV.forEach(item => {
          if(item && item.url) {
            this.fileList.push({url: item.url.indexOf('http') >= 0 ? item.url : '//' + item.url, fullTime: item.fullTime || '', shortTime: item.shortTime || ''})
          }
        })

      }
    }
  },
},
mounted() {
  // if (this.picture && this.fileList.length === 0) {
  //   this.fileList.push({url: '//' + this.picture})
  // }
  this.fileList= []
  if(this.files && this.files.length > 0 && this.fileList.length === 0) {
    this.files.forEach(item => {
      this.fileList.push({url: item.url.indexOf('http') >= 0 ? item.url : '//' + item.url, fullTime: item.fullTime || '', shortTime: item.shortTime || ''})
    })
  }
  this.getCors();
},
methods: {

  beforeDelete(fileRaw) {
    const _this = this
    showConfirmDialog({
      title: '提示',
      message:
        '确认删除这张照片么？',
    }).then(() => {
      _this.$emit("deleteFile", {
        type: _this.type,
        url: fileRaw.url
      })
      _this.fileList.forEach((item, index) => {
        if(item.url === fileRaw.url) {
          _this.fileList.splice(index, 1)
        }
      })
    }).catch(() => {
    })

  },
  afterRead(fileRaw) {
    fileRaw.status = 'uploading';
    fileRaw.message = '上传中...';
    let file = fileRaw.file
    var _this = this;
    var fileSuffix = file.name.substr(file.name.lastIndexOf('.')+1, file.name.length)
    let header = ''
    let imageName = this.uuid()
    if(fileSuffix === 'heic' || fileSuffix === 'HEIC' || fileSuffix === 'heif' || fileSuffix === 'HEIF') {
      header = {
        'Pic-Operations': '{"is_pic_info": 1,"rules": [{"fileid": "'+imageName+'.jpg","rule": "imageMogr2/format/jpg"}]}' 
      }
    }
    this.cors.putObject({
      Bucket: this.corsConfig.bucket, /* 填入您自己的存储桶，必须字段 */
      Region: this.corsConfig.region,  /* 存储桶所在地域，例如ap-beijing，必须字段 */
      Key: this.corsConfig.key + imageName + '.' +fileSuffix,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
      Body: file,
      Headers: header || {},
      onProgress: function(progressData) {
        // console.log(progressData)
      }
    }, (err, data) => {
      console.log(err)
      console.log(data)
      if(err) {
        fileRaw.status = 'failed';
        fileRaw.message = '上传失败';
        return false
      }
      console.log(data.headers.date)
      console.log(moment(data.headers.date).format('M/D HH:mm'))
      let fileLocation = ''
      if(fileSuffix === 'heic' || fileSuffix === 'HEIC' || fileSuffix === 'heif' || fileSuffix === 'HEIF') {
        fileLocation = data.UploadResult.ProcessResults.Object.Location
      }else{
        fileLocation = data.Location
      }
      fileRaw.shortTime = moment(data.headers.date).format('M/D HH:mm')
      fileRaw.status = '';
      fileRaw.message = '';
      fileRaw.url = fileLocation
      _this.$emit("uploadSucc", {
        type: _this.type,
        url: fileLocation,
        fullTime: moment(data.headers.date).format('YYYY-MM-DD HH:mm:ss'),
        shortTime: moment(data.headers.date).format('M/D HH:mm')
      })
      _this.getCors()
    })
  },
  getCors() {
    this.cors = new CORSSDK({
      getAuthorization: this.getAuthorization
    })
  },
  getAuthorization (options, callback) {
    http.get('http://cnf2022adminserver.shanghaistroke-cnf.com/common/tencent/cors/authorization').then(res => {
      let credentials = res.data
      let result = {
        TmpSecretId: credentials.tmpSecretId,
        TmpSecretKey: credentials.tmpSecretKey,
        SecurityToken: credentials.sessionToken,
        // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
        StartTime: credentials.startTime, // 时间戳，单位秒，如：1580000000
        ExpiredTime: credentials.expiredTime, // 时间戳，单位秒，如：1580000000
      }
      this.corsConfig = {
        ...result,
        ...this.corsConfig
      }
      if(callback) {
        callback(result)
      }
    })
  },
  // Record(params) {
  //   baseService.post('/pm/afffile/record', params)
  // },
  uuid () {
    var s = []
    var hexDigits = '0123456789abcdefghi'
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-'

    var uuid = s.join('')
    return uuid
  },

}
});
</script>
<style>
.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
</style>
